<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>报告列表</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/css/bootstrap-icons.css" rel="stylesheet">
    <link href="/css/sweetalert2.min.css" rel="stylesheet">
    <link href="/css/select2.min.css" rel="stylesheet" />
    <style>
        .navbar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .navbar-brand {
            font-weight: 600;
            color: #4f46e5;
        }
        
        .nav-link {
            color: #4b5563;
            transition: all 0.3s ease;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
        }
        
        .nav-link:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }
        
        .nav-link.active {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }
        
        .navbar-toggler {
            border: none;
            padding: 0.5rem;
        }
        
        .navbar-toggler:focus {
            box-shadow: none;
            outline: none;
        }
        
        .dropdown-menu {
            border: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
        }
        
        .dropdown-item {
            padding: 0.5rem 1rem;
            color: #4b5563;
            transition: all 0.3s ease;
        }
        
        .dropdown-item:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }
        
        @media (max-width: 768px) {
            .navbar-nav {
                padding: 1rem 0;
            }
            .nav-link {
                padding: 0.5rem 1rem;
            }
        }
        .summary-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            overflow: hidden;
        }
        
        .summary-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(31, 38, 135, 0.25);
        }
        
        .section-title {
            position: relative;
            padding-left: 1rem;
            margin-bottom: 1.5rem;
            font-weight: 600;
            color: #1f2937;
        }
        
        .section-title::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 24px;
            background: linear-gradient(to bottom, #6366f1, #4f46e5);
            border-radius: 2px;
        }

        .search-area {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }

        .report-card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 1rem;
            border: none;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .report-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        .report-info {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
            color: #6b7280;
        }

        .report-info i {
            width: 20px;
            margin-right: 0.5rem;
            color: #4f46e5;
        }

        .qr-code-container {
            text-align: center;
            padding: 20px;
        }

        #qrcode {
            display: inline-block;
            padding: 10px;
            background: white;
            border-radius: 8px;
        }

        #qrcode img {
            display: block;
            margin: 0 auto;
        }

        @media (max-width: 768px) {
            .search-area {
                padding: 1rem;
            }
            
            .report-card {
                padding: 0.75rem;
            }
        }

        .swal2-container {
            z-index: 10000 !important;
        }

        .modal-backdrop {
            z-index: 9999 !important;
        }

        .modal {
            z-index: 10000 !important;
        }

        .select2-container {
            width: 100% !important;
        }

        .select2-selection {
            height: 38px !important;
            padding: 5px !important;
            border: 1px solid #ced4da !important;
            border-radius: 0.375rem !important;
        }

        .select2-selection__arrow {
            height: 36px !important;
        }

        .select2-container--default .select2-selection--single {
            background-color: #fff;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 28px;
            color: #212529;
        }

        .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #6c757d;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #4f46e5;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg sticky-top">
        <div class="container">
            <a class="navbar-brand" href="/index">
                <i class="bi bi-clipboard-data me-2"></i>运维年报系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <i class="bi bi-list"></i>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/index">
                            <i class="bi bi-house me-1"></i>首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/hospitals/hospital-import">
                            <i class="bi bi-hospital me-1"></i>医院管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/report-list">
                            <i class="bi bi-file-text me-1"></i>报告列表
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/yearEndReview">
                            <i class="bi bi-file-text me-1"></i>值班表生成
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-1"></i>
                            <span th:text="${userName}">用户名</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="#" onclick="openChangePasswordModal()">
                                    <i class="bi bi-key me-2"></i>修改密码
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item text-danger" href="/logout">
                                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                                </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 修改密码模态框 -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">修改密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">原密码</label>
                        <input type="password" class="form-control" id="oldPassword">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">确认新密码</label>
                        <input type="password" class="form-control" id="confirmPassword">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="changePassword()">确认修改</button>
                </div>
            </div>
        </div>
    </div>

    <div class="page-background bg-report-list"></div>
    <div class="wave-bottom"></div>
    
    <div class="container mt-4">
        <div class="summary-card p-4">
            <div class="section-title">
                <i class="bi bi-list-ul me-2"></i>医院报告列表
            </div>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="row g-3">
                    <div class="col-md-5">
                        <label class="form-label">医院</label>
                        <select class="form-select" id="hospitalSelect">
                            <option value="">全部医院</option>
                            <option th:each="hospital : ${hospitals}"
                                    th:value="${hospital.hospitalId}"
                                    th:text="${hospital.hospitalName}">医院名称</option>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">年度</label>
                        <select class="form-select" id="yearSelect">
                            <option value="">全部年度</option>
                            <option th:each="year : ${years}"
                                    th:value="${year}"
                                    th:text="${year + '年'}">2024年</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button class="btn btn-primary w-100" onclick="searchReports()">
                            <i class="bi bi-search me-2"></i>查询
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 报告列表 -->
            <div id="reportList"></div>
        </div>
    </div>

    <!-- QR Code Modal -->
    <div class="modal fade" id="qrCodeModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">扫描二维码查看报告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="qr-code-container">
                        <div id="qrcode"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/sweetalert2.js"></script>
    <script src="/js/qrcode.min.js"></script>
    <script src="/js/select2.min.js"></script>
    <script>
        let qrcode = null;
        const qrCodeModal = new bootstrap.Modal(document.getElementById('qrCodeModal'));
        
        // 修改密码模态框实例
        let changePasswordModal;
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
            
            // 初始化Select2
            $('#hospitalSelect').select2({
                placeholder: '请选择医院',
                allowClear: true,
                width: '100%',
                language: {
                    noResults: function() {
                        return "没有找到匹配的医院";
                    }
                }
            });

            // 监听Select2变化
            $('#hospitalSelect').on('change', function() {
                const hospitalId = $(this).val();
                // 可以在这里添加其他处理逻辑
            });
            
            searchReports();
        });

        function searchReports() {
            const hospitalId = document.getElementById('hospitalSelect').value;
            const year = document.getElementById('yearSelect').value;
            
            // 显示加载中
            Swal.fire({
                title: '加载中...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => {
                    Swal.showLoading();
                }
            });

            fetch(`/api/reports/search?hospitalId=${hospitalId}&year=${year}`)
                .then(response => response.json())
                .then(reports => {
                    Swal.close();
                    displayReports(reports);
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '加载失败',
                        text: '获取报告列表时发生错误',
                        confirmButtonText: '确定'
                    });
                });
        }

        function displayReports(reports) {
            const reportList = document.getElementById('reportList');
            
            if (reports.length === 0) {
                reportList.innerHTML = `
                    <div class="text-center py-4">
                        <i class="bi bi-inbox text-muted" style="font-size: 2rem;"></i>
                        <p class="text-muted mt-2">暂无报告数据</p>
                    </div>
                `;
                return;
            }
            
            reportList.innerHTML = reports.map(report => `
                <div class="report-card">
                    <div class="report-info">
                        <i class="bi bi-hospital"></i>
                        <span>医院名称：${report.hospitalName}</span>
                    </div>
                    <div class="report-info">
                        <i class="bi bi-hash"></i>
                        <span>医院ID：${report.hospitalId}</span>
                    </div>
                    <div class="report-info">
                        <i class="bi bi-calendar-event"></i>
                        <span>年度：${report.demandYear}年</span>
                    </div>
                    <div class="report-info">
                        <i class="bi bi-clock"></i>
                        <span>创建时间：${formatDateTime(report.createTime)}</span>
                    </div>
                    <div class="text-end mt-3">
                        <button class="btn btn-outline-primary btn-sm me-2" style="border-color:#a0c33a;color: #a0c33a">
                            <i class="bi bi-box-arrow-in-up-right me-2"><a style="margin-left: 10px;color: #a0c33a;text-decoration: none;font-style: normal" href="${report.reportUrl}">查看报告</a></i>
                        </button>
                        <button class="btn btn-outline-primary btn-sm me-2" onclick="showQRCode('${report.reportUrl}')">
                            <i class="bi bi-qr-code me-2"></i>查看二维码
                        </button>
                        <button class="btn btn-outline-success btn-sm" onclick="downloadQRCode('${report.reportUrl}', '${report.hospitalName}_${report.demandYear}年报告二维码')">
                            <i class="bi bi-download me-2"></i>下载二维码
                        </button>
                    </div>
                </div>
            `).join('');
        }

        function showQRCode(url) {
            const qrcodeDiv = document.getElementById('qrcode');
            qrcodeDiv.innerHTML = ''; // 清除旧的二维码
            
            // 创建新的二维码，提高清晰度
            qrcode = new QRCode(qrcodeDiv, {
                text: url,
                width: 400,  // 增加尺寸提高清晰度
                height: 400,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
            
            // 添加Logo
            setTimeout(() => {
                const img = qrcodeDiv.querySelector('img');
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const logoImg = new Image();
                
                // 提高logo图片质量
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                
                logoImg.onload = function() {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    
                    // 绘制二维码
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    
                    // 绘制logo，稍微减小logo比例提升清晰度
                    const logoSize = canvas.width * 0.18; // logo大小为二维码的18%
                    const logoX = (canvas.width - logoSize) / 2;
                    const logoY = (canvas.height - logoSize) / 2;
                    
                    // 添加白色背景和边框
                    ctx.fillStyle = '#FFFFFF';
                    ctx.fillRect(logoX - 2, logoY - 2, logoSize + 4, logoSize + 4);
                    
                    ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize);
                    
                    // 替换原始图片
                    img.src = canvas.toDataURL('image/png', 1.0); // 使用最高质量
                };
                
                logoImg.src = '/images/logo.jpg';
            }, 50);
            
            qrCodeModal.show();
        }

        function downloadQRCode(url, filename) {
            const qrcodeDiv = document.createElement('div');
            
            // 创建高清二维码
            const tempQrcode = new QRCode(qrcodeDiv, {
                text: url,
                width: 800,  // 下载版本使用更大尺寸
                height: 800,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
            
            setTimeout(() => {
                const img = qrcodeDiv.querySelector('img');
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const logoImg = new Image();
                
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                
                logoImg.onload = function() {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    
                    // 绘制二维码
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    
                    // 绘制logo
                    const logoSize = canvas.width * 0.18;
                    const logoX = (canvas.width - logoSize) / 2;
                    const logoY = (canvas.height - logoSize) / 2;
                    
                    // 添加白色背景和边框
                    ctx.fillStyle = '#FFFFFF';
                    ctx.fillRect(logoX - 2, logoY - 2, logoSize + 4, logoSize + 4);
                    
                    ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize);
                    
                    // 创建下载链接
                    const link = document.createElement('a');
                    link.download = filename + '.png';
                    link.href = canvas.toDataURL('image/png', 1.0);
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                };
                
                logoImg.src = '/images/logo.jpg';
            }, 50);
        }

        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '--';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
        }

        // 打开修改密码模态框
        function openChangePasswordModal() {
            if (changePasswordModal) {
                changePasswordModal.show();
            }
        }

        function validatePassword(password) {
            const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
            return regex.test(password);
        }

        function changePassword() {
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // 清空输入框
            function clearInputs() {
                document.getElementById('oldPassword').value = '';
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmPassword').value = '';
            }

            // 验证输入
            if (!oldPassword || !newPassword || !confirmPassword) {
                Swal.fire({
                    icon: 'warning',
                    title: '请填写完整',
                    text: '请填写所有密码字段',
                    confirmButtonText: '确定'
                });
                return;
            }

            if (newPassword !== confirmPassword) {
                Swal.fire({
                    icon: 'error',
                    title: '密码不匹配',
                    text: '新密码与确认密码不一致',
                    confirmButtonText: '确定'
                });
                clearInputs();
                return;
            }

            // 验证密码强度
            if (!validatePassword(newPassword)) {
                Swal.fire({
                    icon: 'error',
                    title: '密码强度不足',
                    text: '密码必须包含大小写字母和数字，且长度至少为8位',
                    confirmButtonText: '确定'
                });
                clearInputs();
                return;
            }

            // 显示加载中
            Swal.fire({
                title: '处理中...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // 发送修改密码请求
            fetch('/api/user/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldPassword: oldPassword,
                    newPassword: newPassword
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭修改密码模态框
                    if (changePasswordModal) {
                        changePasswordModal.hide();
                    }
                    
                    // 清空输入
                    clearInputs();
                    
                    // 显示成功消息并跳转
                    Swal.fire({
                        icon: 'success',
                        title: '修改成功',
                        text: '密码已成功修改，请重新登录',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        confirmButtonText: '确定'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '/logout';
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '修改失败',
                        text: data.message || '原密码错误或系统异常，请重试',
                        confirmButtonText: '确定'
                    });
                    clearInputs();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '系统错误',
                    text: '发生未知错误，请重试',
                    confirmButtonText: '确定'
                });
                clearInputs();
            });
        }
    </script>
</body>
</html> 